package com.zhihuitong.meeting.net.callback;

import android.util.Log;

import com.lzy.okgo.exception.HttpException;
import com.lzy.okgo.exception.StorageException;
import com.lzy.okgo.model.Response;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * 作者： lilingjie
 * 时间 2017/9/5.
 * 文件描述：对jsonCallback进行包装,适应服务端接口
 * 版本号：V 1.0
 **/

public abstract class MyCallBack<T> extends JsonCallback<T> {
    private static final String TAG = MyCallBack.class.getSimpleName();

    @Override
    public void onSuccess(Response<T> response) {
        T body = response.body();
        if (null != body) {

            success(body);
        } else {
            error(response.message());
        }
    }


    public abstract void success(T body);

    public abstract void error(String msg);

    @Override
    public void onError(Response<T> response) {
        Throwable exception = response.getException();
        if (null == exception) {
            error("连接服务器时发生未知错误~" + response.message());
            return;
        }
        if (exception instanceof UnknownHostException || exception instanceof ConnectException) {
            Log.d(TAG, "您好，网络异常，请稍后重试");
            error("您好，网络异常，请稍后重试");
        } else if (exception instanceof SocketTimeoutException) {
            Log.d(TAG, "网络连接超时");
            error("网络连接超时");
        } else if (exception instanceof HttpException) {
            Log.d(TAG, "服务端响应404或500");
            error(((HttpException) exception).getMessage());
        } else if (exception instanceof StorageException) {
            Log.d(TAG, "SD卡不存在或没有权限");
            error("SD卡不存在或没有权限");
        } else if (exception instanceof IllegalStateException) {
            String message = exception.getMessage();//这里处理前面自己抛出来的异常信息
            Log.d(TAG, message);
            error(message);
        } else {//其他的未知异常
            error(exception.toString());
            exception.printStackTrace();
        }
    }
}
